package com.sunday.shoufen.ui;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.adapter.CommonAdapter;
import com.sunday.common.widgets.adapter.ViewHolder;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.shoufen.R;
import com.sunday.shoufen.base.BaseApp;
import com.sunday.shoufen.base.BaseLazyFragment;
import com.sunday.shoufen.entity.FanEntity;
import com.sunday.shoufen.entity.Fans;
import com.sunday.shoufen.http.ApiClient;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.common.widgets.EmptyLayout.HIDE_LAYOUT;
import static com.sunday.common.widgets.EmptyLayout.NODATA;

/**
 * Created by 刘涛 on 2017/10/25.
 */

public class FansListFragment extends BaseLazyFragment {

    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.group_total_score)
    TextView groupTotalScore;


    private long memberId;
    private int pageNo = 1, lastVisibleItem;

    private List<Fans> dataSet = new ArrayList<>();
    private CommonAdapter<Fans> adapter;
    private boolean isCanloadMore;
    private LinearLayoutManager layoutManager;
    private int sort;


    public static FansListFragment newInstance(int sort) {
        FansListFragment fragment = new FansListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("sort", sort);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            sort = getArguments().getInt("sort");
        }
    }

    public int getSort() {
        return sort;
    }

    public void setSort(int sort) {
        this.sort = sort;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isPrepared = true;
        lazyLoad();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.layout_fans_fragment_recycler, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        if (!isPrepared || !isVisible) {
            return;
        }
        initRefreshLayout();
        isPrepared = false;
        memberId = BaseApp.getInstance().getMember().getId();
        getData();
    }


    private void initRefreshLayout() {
        adapter = new CommonAdapter<Fans>(mContext, R.layout.list_fans_item, dataSet) {
            @Override
            public void convert(ViewHolder holder, Fans fans) {
                bind(holder, fans);
            }
        };
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());


        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (isCanloadMore) {
                    pageNo++;
                    getData();
                } else {
                    refreshlayout.finishLoadmore();
                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNo = 1;
                getData();
            }
        });

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo = 1;
                getData();
            }
        });

    }

    private void bind(ViewHolder holder, final Fans fans) {
        CircleImageView userLogo = holder.getView(R.id.fans_logo);
        TextView userName = holder.getView(R.id.fans_name);
        TextView userTime = holder.getView(R.id.fans_time);
        TextView recName = holder.getView(R.id.rec_name);
        TextView consumeScore = holder.getView(R.id.consume_score);
        Glide.with(mContext)
                .load(fans.getLogo())
                .error(R.mipmap.ic_default)
                .into(userLogo);
        userName.setText(fans.getNickName() == null ? fans.getMobile() : fans.getNickName());
        userTime.setText(fans.getTime());
        recName.setVisibility(sort == 1 ? View.GONE : View.VISIBLE);
        recName.setText("推荐人:" + (TextUtils.isEmpty(fans.getRecName()) ? fans.getRecMobile() : fans.getRecName()));
        consumeScore.setText(String.format("本月消费积分：%s", fans.getScore().setScale(2, RoundingMode.HALF_UP)));

        holder.setOnClickListener(R.id.rl_fans, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sort == 2) {
                    return;
                }
                AlertDialog dialog = new AlertDialog.Builder(mContext).setTitle("温馨提示")
                        .setMessage("确认解绑吗")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                unBindFans(fans.getId());
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();
            }
        });

    }

    private void unBindFans(long fansId) {
        Call<ResultDO> call = ApiClient.getApiAdapter().unbindMember(fansId);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "解绑成功");
                    pageNo = 1;
                    getData();
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {

            }
        });
    }

    private void getData() {
        showLoadingDialog(0);
        Call<ResultDO<FanEntity>> call = ApiClient.getApiAdapter().getMyMember(1, memberId, sort, pageNo, Constants.PAGE_SIZE);
        call.enqueue(new Callback<ResultDO<FanEntity>>() {
            @Override
            public void onResponse(Call<ResultDO<FanEntity>> call, Response<ResultDO<FanEntity>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                refreshLayout.finishLoadmore();
                refreshLayout.finishRefresh();
                if (response.body().getCode() == 0) {
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult().getMembers());
                    if (response.body().getResult().getMembers().size() == Constants.PAGE_SIZE) {
                        isCanloadMore = true;
                    } else {
                        isCanloadMore = false;
                    }
                    ((MyFansActivity) getActivity()).updateNumber(sort - 1, response.body().getResult().getCount());
                    if (sort == 1) {
                        groupTotalScore.setText("钻石会员本月总消费积分:" + response.body().getResult().getMembersTotalScore().setScale(2, RoundingMode.HALF_UP));
                    } else {
                        groupTotalScore.setText("黄金会员本月总消费积分:" + response.body().getResult().getMembersTotalScore().setScale(2, RoundingMode.HALF_UP));

                    }
                    emptyLayout.setErrorType(dataSet.size() > 0 ? HIDE_LAYOUT : NODATA);
                    adapter.notifyDataSetChanged();
                } else

                {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<FanEntity>> call, Throwable t) {
                refreshLayout.finishLoadmore();
                refreshLayout.finishRefresh();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            pageNo = 1;
            memberId = BaseApp.getInstance().getMember().getId();
            getData();
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
